import React, { useState, useRef, useMemo } from 'react'
import { useMouse, useThrottle } from 'ahooks'

import { outOfArea } from '../../../util/index'
import video from '../../../store/video'
import scss from './rate-options.module.scss'

const RateOptions = () => {
  const [visible, setVisible] = useState(false)
  const [optId, setOptId] = useState('')
  const [rateLabel, setRateLabel] = useState('倍速')

  const btnRef = useRef()
  const optRef = useRef()

  const mouse = useMouse()
  const throttledValue = useThrottle(mouse, { wait: 200 })

  useMemo(() => {
    if (visible) {
      if (outOfArea(optRef.current, throttledValue) && outOfArea(btnRef.current, throttledValue)) {
        setVisible(false)
      }
    }
  }, [throttledValue])

  function Options() {
    const opts = [
      {
        label: '4X',
        value: 4,
      },
      {
        label: '2X',
        value: 2,
      },
      {
        label: '1X',
        value: 1,
      },
    ]

    function onMouseDown(val) {
      const screen = video.findScreenById(video.curScreenId)
      if (screen && screen?.player) {
        const video = screen.player.video
        video.playbackRate = val
        setRateLabel(val === 1 ? '倍速' : `${val}X`)
        setVisible(false)
      }
    }

    return opts.map(({ value, label }, index) => {
      return (
        <div
          className={scss.rateOpt}
          key={index}
          onMouseDown={() => onMouseDown(value)}
          onMouseOver={() => setOptId(index)}
          style={{ background: index === optId ? '#646464' : '#222222' }}
        >
          <span>{label}</span>
        </div>
      )
    })
  }

  return (
    <div style={{ position: 'relative', cursor: 'pointer' }} onMouseEnter={() => setVisible(true)}>
      {/* 分屏选项 */}
      <div ref={optRef} style={{ display: visible ? 'block' : 'none' }} className={scss.panel}>
        <div className="item">
          <Options />
        </div>
      </div>
      {/* 倍速按钮 */}
      <div ref={btnRef} className={scss.btn}>
        <span>{rateLabel}</span>
      </div>
    </div>
  )
}

export default RateOptions
